/*
 * @Author: Season
 * @Date: 2020-08-11 15:43:35
 * @LastEditTime: 2020-08-12 11:37:45
 * @FilePath: \blog-chain\src\websocket.ts
 */
// websocket
import * as WebSocket from 'ws';
// eslint-disable-next-line no-unused-vars
import BlockChain from './blockChain';

const initMessageHandler = (ws: WebSocket) => {
  ws.on('message', (message: string) => {
    const msg = JSON.parse(message);
    if (msg.type !== 'mine') {
      console.log(msg.data);
    } else {
      console.log(msg.data, 'mine');
    }
    // console.log('received: %s from %s', message, clientName);

    // // 广播消息给所有客户端
    // server.clients.forEach((client) => {
    //   if (client.readyState === WebSocket.OPEN) {
    //     client.send(`${clientName} -> ${message}`);
    //   }
    // });
  });
};

const initWebsocket = (p2pPort: number) => {
  const server = new WebSocket.Server({ port: p2pPort });
  const sockets: WebSocket[] = [];

  server.on('open', () => {
    console.log('connected');
  });

  server.on('close', () => {
    console.log('disconnected');
  });

  server.on('connection', (ws, req) => {
    sockets.push(ws);
    const ip = req.connection.remoteAddress as string;
    const port = req.connection.remotePort as number;
    const clientName = ip + port;

    console.log('%s is connected', clientName);

    // 发送欢迎信息给客户端
    ws.send(JSON.stringify({
      data: `Welcome ${clientName}`,
    }));

    initMessageHandler(ws);
  });

  return sockets;
};

export { initWebsocket, initMessageHandler };
